(function(_window) {
  var kbg = {};

  kbg.bridge = null;
  kbg.version = '0.1.0';

  // ready 回调函数集
  var readyCallbackStack = [];

  // 在酷办公上增加命名空间
  kbg.__register = function(namespace, value) {
    var sp = namespace.split('.');
    var obj = kbg;

    for(var i = 0, len = sp.length; i < len; i++) {
      if(i === len - 1) {
        obj[sp[i]] = value;
      } 
      if(typeof obj[sp[i]] === 'undefined') {
        obj[sp[i]] = {};
      }
      obj = obj[sp[i]];
    }
  };

  // kbg.ready = function(callback) {
  //   if(typeof callback === 'function') {
  //     if(kbg.bridge && !readyCallbackStack.length) {
  //       callback();
  //     } else {
  //       readyCallbackStack.push(callback);
  //     }
  //   }
  // };
  // 
  function isIOS() {
    var ua = navigator.userAgent.toLowerCase();
    return /iphone|ipad|ipod/.test(ua);
  }

  /**
   * 初始化 sdk 完成回调
   * @todo  支持回调队列
   */
  kbg.ready = function(callback) {
    // 目前 Android 访问 wvjbscheme 协议会出错
    if(isIOS()) {
      kbg.setupWebViewJavascriptBridge(function(bridge) {
        kbg.bridge = bridge;
        kbg.isReady = true;
        callback && callback();
      });
    }
  };

  /**
   * 初始化 sdk 失败回调
   */
  kbg.error = function(callback){};

  /**
   *  此为js接入框架的函数
   */
  kbg.setupWebViewJavascriptBridge = function(callback) {
    if (window.WebViewJavascriptBridge) {
      return callback(WebViewJavascriptBridge);
    }
    if (window.WVJBCallbacks) {
      return window.WVJBCallbacks.push(callback);
    }
    window.WVJBCallbacks = [callback];
    var WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function() {
      document.documentElement.removeChild(WVJBIframe);
    }, 0);
  };

  /**
   * 设置标题
   * biz.navigation.setTitle
   * @param  {object}  params
   */
  
  /**
   * 设置左导航按钮
   * biz.navigation.setLeft
   * @param  {object}  params
   */
  
  /**
   * 设置右导航按钮
   * biz.navigation.setRight
   * @param  {object}  params
   */
  
  /**
   * 关闭 webView
   * biz.navigation.close
   */
  
  /**
   * 打开应用内页面
   * biz.util.open
   * @param  {object}  params
   * - params.name {string}  要打开的页面 id
   */
  var apiList = [
    'runtime.info',
    'biz.navigation.setTitle', 'biz.navigation.setLeft', 'biz.navigation.setRight', 'biz.navigation.close',
    'device.geolocation.get', 'biz.map.locate', 'biz.map.view',
    'biz.util.open', 'biz.util.share', 'biz.util.previewImage'
    ];
  var noop = function () {};
  var clickEventMap = {
    'biz.navigation.setLeft': 'biz.navigation.leftClick',
    'biz.navigation.setRight': 'biz.navigation.rightClick',
    'biz.navigation.setTitle': 'biz.navigation.titleClick',

  };

  apiList.forEach(function(key) {
    kbg.__register(key, function(params) {
      // callApi();
      params = params || {};
      onSuccess = params.onSuccess || noop;
      onFail = params.onFail || noop;

      switch(key) {
        // 设置左右导航按钮时，注册点击事件
        case 'biz.navigation.setLeft':
        case 'biz.navigation.setRight':
        case 'biz.navigation.setTitle':
          if(params.control) {
            onSuccess = noop;
            // 如果 control 参数为 true，则将 onSuccess 设置为点击回调
            if(kbg.bridge) {
              kbg.bridge.registerHandler(clickEventMap[key], params.onSuccess);
            }
          }
          break;
      }

      if(kbg.bridge) {
        kbg.bridge.callHandler(key, params, function(response) {
          response = JSON.parse(response);
          if(response.responsecode == '0') {
            onSuccess(response);
          } else {
            onFail(response);
          }
        });
      }
    });
  });

  _window.kbg = kbg;

}(this));
